﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class keybindsManager : MonoBehaviour
{
    private static keybindsManager instance;
    public static keybindsManager MyInstance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<keybindsManager>();
            }
            return instance;
        }
    }

    public Dictionary<string, KeyCode> KeyBinds { get ; private set ; }
    public Dictionary<string, KeyCode> actionBinds { get ; private set ; }
    private string bindname;
    // Start is called before the first frame update
    void Start()
    {
        KeyBinds = new Dictionary<string, KeyCode>();
        actionBinds = new Dictionary<string, KeyCode>();
        bindKey("ACT1", KeyCode.Alpha1);
        bindKey("ACT2", KeyCode.Alpha2);
        bindKey("ACT3", KeyCode.Alpha3);
        bindKey("ACT4", KeyCode.Alpha4);
        bindKey("ACT5", KeyCode.Alpha5);
        bindKey("ACT6", KeyCode.Alpha6);
        bindKey("ACT7", KeyCode.Alpha7);
        bindKey("ACT8", KeyCode.Alpha8);
        bindKey("ACT9", KeyCode.Alpha9);
        bindKey("ACT10", KeyCode.Alpha0);
        bindKey("ACT11", KeyCode.Minus);
        bindKey("ACT12", KeyCode.Equals);
        bindKey("character", KeyCode.C);
        bindKey("journal", KeyCode.J);
        bindKey("inventory", KeyCode.I);
        bindKey("SkillBook", KeyCode.B);
        bindKey("CharacterList", KeyCode.L);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void bindKey(string key, KeyCode bind)
    {
        Dictionary<string, KeyCode> CurDict = KeyBinds;
        if (key.Contains("ACT"))
        {
            CurDict = actionBinds;
        
        }
        if (!CurDict.ContainsKey(key))
        {
            CurDict.Add(key, bind);
            
        }
        else if (CurDict.ContainsValue(bind)){
            string temp = CurDict.FirstOrDefault(x => x.Value == bind).Key;
            CurDict[temp] = KeyCode.None;
        }
        CurDict[key] = bind;
        bindname = string.Empty;
        UIManager.MyInstance.updateButtonText(key, bind);
    }
    public void keybindOnClick(string bindname)
    {
        this.bindname = bindname;
    }
   public void OnGUI()
    {
        if(bindname != string.Empty)
        {
            Event tempEvent=Event.current;
            if (tempEvent.isKey)
            {
                bindKey(bindname, tempEvent.keyCode);
            }
        }
    }
}
